package com.chezhujie.www.controller;

import com.chezhujie.www.core.page.Pagination;
import com.chezhujie.www.core.quartz.AppMap;
import com.chezhujie.www.domain.Czjbusiness;
import com.chezhujie.www.domain.Czjexpress;
import com.chezhujie.www.domain.Czjorder;
import com.chezhujie.www.domain.Xyuser;
import com.chezhujie.www.domain.vo.BusinOrder;
import com.chezhujie.www.domain.vo.CommodityDetail;
import com.chezhujie.www.enums.OrderStatus;
import com.chezhujie.www.service.*;
import com.chezhujie.www.utils.ConvertObj;
import com.chezhujie.www.utils.LocalDateTime;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/businorder")
public class CzjorderAdminController extends BaseController {

	@Autowired
	private CzjorderService czjorderService;
	@Autowired
	private CzjbusinessService czjbusinessService;
	
	@Autowired
	private CzjexpressService czjexpressService;
	@Autowired
	private CzjawarduseService czjawarduseService;
	@Autowired
	private CzjawardstockService czjawardstockService;
	@Autowired
	private CzjusecouponService czjusecouponService;

	@RequestMapping("list")
	public String list(Integer pageNo, Integer pageSize,
			HttpServletRequest req, HttpServletResponse resp, String orderCode,
			String phoneNo, Integer status, Date createTimeStart,
			Date createTimeEnd, HttpSession httpSession, ModelMap model) {
		setMsg(req,model);
		Map<String, Object> map = new HashMap<String, Object>();
		if (pageNo == null) {
			pageNo = 1;
		}
		if (pageSize == null) {
			pageSize = 20;
		}

		if (null != createTimeStart) {

			map.put("createTimeStart", createTimeStart);
			model.addAttribute("createTimeStart", createTimeStart);
		}

		if (null != createTimeEnd) {

			map.put("createTimeEnd", createTimeEnd);
			model.addAttribute("createTimeEnd", createTimeEnd);
		}
		if (StringUtils.isNotBlank(orderCode)) {
			map.put("orderCode", orderCode);
			model.addAttribute("orderCode", orderCode);
		}
		if (StringUtils.isNotBlank(phoneNo)) {
			map.put("phoneNo", phoneNo);
			model.addAttribute("phoneNo", phoneNo);
		}
		if (null != status) {
			map.put("status", status);
			model.addAttribute("status", status);
		}

		try {
			Xyuser user = (Xyuser) httpSession.getAttribute("user");
			if (null == user) {

				model.addAttribute("error", "用户为空");
				return "nobusin/no";
			} else {
				Czjbusiness czjbusiness = czjbusinessService
						.getBusinessByTuserid(user.getUserId());// 根据用户ID查询businessid
				if (czjbusiness == null) {
					return  "nobusin/nobusin";
				} else {

					map.put("businessId", czjbusiness.getId());
					//添加已售量 、订单总金额
					Map<String,Object> soldOutMap = czjorderService.sumSoldOut(czjbusiness.getId());
					model.addAttribute("allSoldOut", soldOutMap.get("allSoldOut"));
					Map<String,Object> salesAmount = czjorderService.getSalesAmount(czjbusiness.getId());
					model.addAttribute("salesAmount", salesAmount.get("salesAmount"));

					
				}
				Pagination pagination = czjorderService
						.getOrderBybusinessid(pageNo, pageSize, map, model);

				List<Map<String,Object>> list = ConvertObj.toListMap((List<BusinOrder>) pagination.getList());
				Integer status2 = null;
				for (int i = 0; i < list.size(); i++) {
					list.get(i).put("isRefund", 0);//默认没有退款按钮
					status2 = (Integer)list.get(i).get("status");
					if(status2!=null&&status2== OrderStatus.FIN.getIndex()){//订单完成时间
						Date operdate = (Date)list.get(i).get("createtime");
						if((System.currentTimeMillis()-operdate.getTime())>7*24*60*60*1000){
							list.get(i).put("isRefund", 0);
						}else{
							list.get(i).put("isRefund", 1);//有退款按钮
						}
					}
				}
				pagination.setList(list);
				model.addAttribute("pagination", pagination);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "businorder/list";
	}

	@RequestMapping("detail")
	public String detail(@RequestParam(required = true) String id,
			@RequestParam(required = true) String businessid,
			HttpServletRequest req, HttpServletResponse resp,
			HttpSession httpSession, ModelMap model) {

		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("businessId", businessid);
			map.put("id", id);
			BusinOrder businOrder = czjorderService
					.getOrderBybusinessidAndOrderId(map);
			model.addAttribute("entity", businOrder);

			//优惠券
			czjusecouponService.setCouponsByOrderCode(businOrder.getOrderCode(),businOrder.getCouponsId(),model);


			List<CommodityDetail> list=new  ArrayList<CommodityDetail>();
			
			
			CommodityDetail e=null;
			for(int i=0;i<businOrder.getBusinOrdercommodity().size();i++){
				e=new CommodityDetail();
				if(null != businOrder.getBusinOrdercommodity().get(i) && null != businOrder.getBusinOrdercommodity().get(i).getCommodityName() ){
					
					e.setCommodityName(businOrder.getBusinOrdercommodity().get(i).getCommodityName());
				}
				/*if(null != businOrder.getBusinOrdercommodity().get(i) && null != businOrder.getBusinOrdercommodity().get(i).getSalePrice() ){
					
					e.setSalePrice(businOrder.getBusinOrdercommodity().get(i).getSalePrice());
				}*/
		
				if(null != businOrder.getOrderDetails().get(i) && null!=businOrder.getOrderDetails().get(i).getAmount() ){
					
					e.setAmount(businOrder.getOrderDetails().get(i).getAmount());
					e.setSalePrice(businOrder.getOrderDetails().get(i).getSalePrice());
				}
	
				
				if(null != businOrder.getBusinOrderImg() && businOrder.getBusinOrderImg().size()>0 && null != businOrder.getBusinOrderImg().get(i) && null!=businOrder.getBusinOrderImg().get(i).getImagePath() ){
					
					e.setImagePath(businOrder.getBusinOrderImg().get(i).getImagePath());
				}
	
			
				
				list.add(e);
			}
			model.addAttribute("list", list);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "businorder/detail";
	}



	@RequestMapping("getExpress")
	public String getExpress(@RequestParam(required = true) String orderCode,
			HttpServletRequest req, HttpServletResponse resp,
			HttpSession httpSession, ModelMap model) {

		try {
				Map<String,Object> map=new HashMap<String, Object>();
				map.put("orderCode", orderCode);
			Czjexpress czjexpress= czjexpressService.getExpressByOrdercode(map);
			if(null==czjexpress){
				model.addAttribute("entity", new Czjexpress());
				
				
			}else{
			model.addAttribute("entity", czjexpress);
			}
			model.addAttribute("orderCode", orderCode);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "businorder/express";
	}
	
	@RequestMapping("svseExpress")
	public String svseExpress(Czjexpress czjexpress,
			HttpServletRequest req, HttpServletResponse resp,
			HttpSession httpSession, ModelMap model) {

		try {
			if(null==czjexpress.getExpressId() || "".equals(czjexpress.getExpressId())){
				czjexpressService.insertCzjexpress(czjexpress);
				List<Czjorder> czjorders=czjorderService.getOrderByOrderCode(czjexpress.getOrderCode());
				if(null!=czjorders && czjorders.size()>0){
					Czjorder czjorder=czjorders.get(0);
					czjorder.setStatus(OrderStatus.WAITFORRECEIVING.getIndex());
					czjorderService.update(czjorder);//修改状态
					AppMap.getBusinOrder().put(czjorder.getId(), LocalDateTime.getDateTime(czjorder.getCreateTime())); //加入到缓存
				}	
			}else{
				czjexpressService.updateCzjexpress(czjexpress);
			}
				
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "redirect:/businorder/list";
	}
	private void setMsg(HttpServletRequest req, ModelMap model) {
		model.addAttribute("failed", req.getParameter("failed"));
		model.addAttribute("success", req.getParameter("success"));
	}
}
